<template>
	<BackgroundImage>
		<!-- 顶部导航 -->
		<TopNavigation :title=" matchId ? `${matchName} - 比赛模式管理` : '比赛模式管理' " backText="赛事业务" titleSub="管理比赛模式和规则" />
		
		<view class="view-container">
            <view class="view-container-left">
                <view class="view-container-left-top"  @click="goToCreateModel">
                    创建模式
                </view>
                <view class="view-container-left-bottom" @click="goToScheduleModel">
                    赛程模式管理
                </view>
            </view>
            <view class="view-container-right">
                <BoxView :titBoxObj="{
                    title: '模式列表',
                    titleCount: `共有${modelList.length}个模式`
                }" padding="0" >
                   <view class="view-container-right-list">
                        <view class="view-container-right-list-item" v-for="model in modelList" :key="model.matchModelId">
                            <view class="view-container-right-list-item-title">
                                <text style="font-size: 16rpx;font-weight: bold;">{{ model.matchModelName }}</text>
                                <view class="next-row">
                                    <view class="id-text"><text>模式ID：</text>{{ model.matchModelId || model.id }}</view>
                                </view>
                                <view class="next-row">
                                    <view class="id-value"><text>赛事ID：</text>{{ model.matchId || '未设置' }}</view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text"><text>赛程模式：</text>{{ model.matchScheduleModelId || '未设置' }}</view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text"><text>模式名称：</text>{{ model.matchModelName || '未设置' }}</view>
                                    <view class="id-value"><text>名称模板：</text>{{ model.nameTemplate || '未设置' }}</view>
                                </view>
                                <view class="next-row">
                                    <view class="id-value"><text>创建方式：</text>{{ getCreateTypeText(model.matchScheduleCreateType)  }}</view>
                                    <view class="id-value"><text>触发类型:</text>{{ getTriggerTypeText(model.triggerType)  }}</view>
                                </view>
                                <view class="next-row">
                                    <view class="id-value"><text>创建时间:</text>{{ formatDate(model.createTime)  }}</view>
                                    <view class="id-text"><text>下次触发:</text>{{ formatDate(model.nextTriggerTime)  }}</view>
                                </view>
                                <view class="next-row">
                                    <view class="id-value"><text>比赛开始:</text>{{ formatDate(model.matchStartTime)  }}</view>
                                    <view class="id-text"><text>比赛结束:</text>{{ formatDate(model.matchEndTime)  }}</view>
                                </view>
                                <view class="next-button">
                                    <view class="next-button-item1" @click.stop="deleteModel(model)">删除</view>
                                    <view class="next-button-item2" @click.stop="editModel(model)">编辑</view>
                                </view>
                            </view>
                        </view>
                   </view>

                </BoxView>
            </view>
	    </view>
	</BackgroundImage>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { onShow, onLoad } from '@dcloudio/uni-app'
import { MatchModelAPI } from '@/api/battle.js'
	import TopNavigation from "@/components/UiView/TopNavigation.vue";
	import BoxView from "@/components/UiView/BoxView.vue";

// 响应式数据
const loading = ref(false)
const matchId = ref('') // 当前赛事ID
const matchName = ref('') // 当前赛事名称

// 模式列表
const modelList = ref([])

// 创建方式选项
const createTypeOptions = ['手动创建', '自动创建', '定时创建']

// 处理URL参数
onLoad((options) => {
  if (options.matchId) {
    matchId.value = options.matchId
  }
  if (options.matchName) {
    matchName.value = decodeURIComponent(options.matchName)
  }
})

// 获取创建方式文本
const getCreateTypeText = (type) => {
  return createTypeOptions[type] || '未知'
}

// 获取触发类型文本
const getTriggerTypeText = (type) => {
  const triggerTypeTextMap = {
    1: '每日触发',
    2: '每周触发',
    3: '每月触发',
    0: '自定义触发'
  }
  return triggerTypeTextMap[type] || '未知'
}

// 加载模式列表
const loadModelList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      pageNum: 0,
      pageSize: 100,
      delFlag: 0
    }
    
    // 如果指定了赛事ID，则只查询该赛事的模式
    if (matchId.value) {
      params.matchId = matchId.value
    }
    
    const result = await MatchModelAPI.page(params)
    
    console.log('获取比赛模式列表结果:', result)
    
    if (result.code === 0) {
      modelList.value = result.data?.list || result.data || []
    } else {
      throw new Error(result.msg || '获取模式列表失败')
    }
  } catch (error) {
    console.error('加载模式列表失败:', error)
    uni.showToast({
      title: error.message || '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 跳转到创建模式页面
const goToCreateModel = () => {
  let url = '/views/match-model-manage/match-model-form'
  if (matchId.value) {
    url += `?matchId=${matchId.value}`
    if (matchName.value) {
      url += `&matchName=${encodeURIComponent(matchName.value)}`
    }
  }
  uni.navigateTo({ url })
}

// 跳转到编辑模式页面
const editModel = (model) => {
  // 使用全局存储传递模式数据，不通过链接参数
  try {
    console.log('准备存储编辑数据:', model)
    // 确保数据可以被序列化，创建一个纯对象副本
    const modelData = {
      matchModelId: model.matchModelId || model.id,
      id: model.matchModelId || model.id,
      matchId: model.matchId || '',
      matchModelName: model.matchModelName || '',
      matchScheduleModelId: model.matchScheduleModelId || '',
      matchScheduleModelName: model.matchScheduleModelName || '', // 添加赛程模式名称
      nameTemplate: model.nameTemplate || '',
      matchScheduleCreateType: model.matchScheduleCreateType !== undefined ? model.matchScheduleCreateType : 0,
      triggerType: model.triggerType !== undefined ? model.triggerType : 0,
      nextTriggerTime: model.nextTriggerTime || null,
      matchStartTime: model.matchStartTime || null,
      matchEndTime: model.matchEndTime || null,
      matchDurationTime: model.matchDurationTime || null,
      createTime: model.createTime || null
    }
    console.log('准备存储的模型数据:', JSON.stringify(modelData, null, 2))
    uni.setStorageSync('editModelData', modelData)
    console.log('数据已存储，准备跳转')
    
    // 如果有赛事ID和名称，也存储起来
    if (matchId.value) {
      uni.setStorageSync('editModelMatchId', matchId.value)
    }
    if (matchName.value) {
      uni.setStorageSync('editModelMatchName', matchName.value)
    }
    
    // 跳转到编辑页面
    uni.navigateTo({
      url: '/views/match-model-manage/match-model-form',
      success: () => {
        console.log('页面跳转成功')
      },
      fail: (err) => {
        console.error('页面跳转失败:', err)
      }
    })
  } catch (error) {
    console.error('存储编辑数据失败:', error)
    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none'
    })
  }
}

// 删除模式
const deleteModel = (model) => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除模式 "${model.matchModelName || model.nameTemplate || model.matchModelId}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await MatchModelAPI.remove({
            matchModelId: model.matchModelId
          })
          
          if (result.code === 0) {
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
            loadModelList()
          } else {
            throw new Error(result.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除模式失败:', error)
          uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '未设置'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN')
}

// 跳转到赛程模式管理页面
const goToScheduleModel = () => {
  uni.navigateTo({
    url: '/views/schedule-model-manage/index'
  })
}

// 页面加载时获取模式列表
onMounted(() => {
  loadModelList()
})

// 页面显示时检查是否需要刷新数据
onShow(() => {
  // 检查是否有刷新标记（编辑或创建成功后设置）
  const needRefresh = uni.getStorageSync('modelListNeedRefresh')
  if (needRefresh) {
    console.log('检测到需要刷新模式列表')
    // 清除刷新标记
    uni.removeStorageSync('modelListNeedRefresh')
    // 刷新数据
    loadModelList()
  } else {
    // 没有刷新标记时也刷新，确保数据最新
    loadModelList()
  }
})
</script>

<style lang="scss" scoped>
	.view-container{
        display: flex;justify-content: space-between;align-items: center;
        height: calc(100vh - 65rpx);
        padding-right: 20rpx;
        overflow: hidden;
        &-right{
            flex: 1;
            height: 100%;overflow: hidden;
            &-list{
                padding: 10rpx;
                overflow: auto;height: calc(100% - 60rpx);
                &-item{
                    background: #F0F0E4;
                    border-radius: 10rpx;
                    padding: 10rpx;
                    margin-bottom: 10rpx;
                    font-size: 14rpx;
                    .next-button{
                        display: flex;justify-content: end;align-items: center;
                        margin-top: 10rpx;
                        &-item1,&-item2{
                            width: 108rpx;
                            height: 30rpx;
                            font-size: 14rpx;
                            display: flex;justify-content: center;align-items: center;
                            padding-bottom: 4rpx;
                            color: #fff;
                        }
                        &-item1{
                            background: url('/static/buttons/button2-1.png') no-repeat center center;
                            background-size: 100% 100%;
                            margin-right: 10rpx;
                        }
                        &-item2{
                            background: url('/static/buttons/button7.png') no-repeat center center;
                            background-size: 100% 100%;
                        }
                    }
                    .next-row{
                        display: flex;justify-content: space-between;align-items: center;
                        margin-top: 10rpx;
                        view{
                            width: 50%;
                        }
                        text{
                            display: inline-block;
                            font-size: 14rpx;
                            color: #99A1A4;
                            width: 70rpx;
                            text-align: right;
                        }
                    }
                }
            }
        }
        &-left{
            display: flex;flex-direction: column;justify-content: center;align-items: center;
            padding: 10rpx 20rpx;
            view{
                width: 118rpx;box-sizing: border-box;padding-bottom: 10rpx;
                height: 90rpx;
                font-size: 15rpx;
                color: #fff;
                display: flex;justify-content: center;align-items: end;
                margin-bottom: 10rpx;
            }
            &-top{
                background: url('/static/view1.png') no-repeat center center;
                background-size: 100% 100%;
            }
            &-bottom{
                background: url('/static/view2.png') no-repeat center center;
                background-size: 100% 100%;
            }
        }
    }
</style>